import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './static'
import store from '@/store/index'
import { Message } from 'element-ui'

Vue.use(VueRouter)


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

let flag = true
router.beforeEach((to, from, next) => {
  if (to.path != '/login') {
    if (!store.state.tokenObj.token) {
      Message.error('登录过期请先登录')
      next('/login')
    } else {
      let a = store.state.routerModule.routerModuleList
      if (flag && a.length != 0) {
        a.forEach(item => {
          item.component = getComponents(item.name)
          router.addRoute('Home',item)
        })
        flag = false
        next({
          ...to,
          replace:true
        })
      }else{
        next()
      }

      
    }
  } else {
    next()
  }
})

function getComponents(path) {
  return () => import(`@/components/${path}`)
}

export default router
